package org.goldfish.demo.apicall.analysis.code.upload;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.goldfish.demo.apicall.analysis.code.di.SpringFXMLLoader;
import org.goldfish.demo.apicall.analysis.code.select.ProjectSelectorController;
import org.goldfish.demo.apicall.analysis.code.upload.messager.interfaces.LargeModelClient;
import org.goldfish.demo.apicall.analysis.code.upload.model.PdfImageAnalysis;
import org.goldfish.demo.apicall.analysis.code.upload.model.PdfImagePanelController;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@RequiredArgsConstructor
@Slf4j
public class PdfAnalysisController {

    private final ExecutorService executor = Executors.newFixedThreadPool(
            Runtime.getRuntime().availableProcessors()
    );

    private final ProjectSelectorController folderSelector;
    private final LargeModelClient largeModelClient;

    @FXML
    private VBox fileContainer;

    private final java.util.function.Consumer<PdfImageAnalysis> imageDisplayHandler = pdfImageAnalysis ->
            Platform.runLater(() -> {
                try {
                    FXMLLoader loader = new SpringFXMLLoader("pdf_image_panel.fxml");
                    VBox panel = loader.load();

                    PdfImagePanelController controller = loader.getController();
                    controller.setPdfImageAnalysis(pdfImageAnalysis);
                    log.info("PDF页面已添加: {} 页面 {}", 
                             pdfImageAnalysis.getFile().getAbsoluteFile(), 
                             pdfImageAnalysis.getPageNumber());

                    fileContainer.getChildren().add(panel);
                } catch (IOException e) {
                    log.error("加载PDF图片面板失败", e);
                } catch (Error e) {
                    log.error("加载PDF图片面板失败", e);
                    System.exit(0);
                }
            });

    public void execute(List<String> paths) throws IOException {
        // 清空之前的容器
        fileContainer.getChildren().clear();

        // 收集所有PDF文件
        List<File> pdfFiles = new ArrayList<>();
        for (String path : paths) {
            File folder = new File(path);
            log.info("扫描路径 {}", path);
            if (!folder.isDirectory()) {
                log.warn("路径不是有效目录: {}", path);
                continue;
            }

            // 查找所有PDF文件
            findPdfFiles(folder, pdfFiles);
        }

        // 处理所有PDF文件
        for (File pdfFile : pdfFiles) {
            executor.submit(() -> {
                try {
                    processPdfFile(pdfFile);
                } catch (Exception e) {
                    log.error("处理PDF文件失败: {}", pdfFile.getAbsoluteFile().getName(), e);
                }
            });
        }
    }

    private void findPdfFiles(File folder, List<File> pdfFiles) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    findPdfFiles(file, pdfFiles);
                } else if (file.getName().toLowerCase().endsWith(".pdf")) {
                    pdfFiles.add(file);
                }
            }
        }
    }

    private void processPdfFile(File pdfFile) throws IOException {
        log.info("正在处理PDF文件 {}", pdfFile.getAbsoluteFile());
        
        try (PDDocument document = PDDocument.load(pdfFile)) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            int pageCount = document.getNumberOfPages();
            
            log.info("PDF文件 {} 包含 {} 页", pdfFile.getName(), pageCount);
            
            // 逐页处理PDF
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = pdfRenderer.renderImageWithDPI(i, 100);
                
                PdfImageAnalysis pdfImageAnalysis = PdfImageAnalysis.builder()
                        .file(pdfFile)
                        .image(image)
                        .pageNumber(i + 1)
                        .build();
                
                // 显示图片
                imageDisplayHandler.accept(pdfImageAnalysis);
                
                // 调用大模型分析图片
                analyzeImageWithModel(pdfImageAnalysis);
            }
        }
    }

    private void analyzeImageWithModel(PdfImageAnalysis pdfImageAnalysis) {
        try {
            // 这里应该调用大模型API分析图片
            // 由于当前LargeModelClient是为文本设计的，我们需要修改或扩展它来处理图片
            // 暂时用模拟响应
            String mockResponse = "这是PDF文件 " + 
                                  pdfImageAnalysis.getFile().getName() + 
                                  " 的第 " + pdfImageAnalysis.getPageNumber() + " 页的分析结果";
            
            pdfImageAnalysis.appendToken(mockResponse);
            log.info("页面 {} 的大模型返回结果:\n{}", 
                     pdfImageAnalysis.getPageNumber(), 
                     pdfImageAnalysis.getResponse());
        } catch (Exception e) {
            log.error("分析PDF页面失败: {}", pdfImageAnalysis.getPageNumber(), e);
        }
    }
}